package com.ita.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

public class TokenUtil {
	
	private volatile static Map<String, Integer> tokenMap = new ConcurrentHashMap<String, Integer>();

	private static final int SUMBIT_TIME = 5;

	private TokenUtil() {

	}

	private static TokenUtil instance = new TokenUtil();

	public static TokenUtil getInstance() {
		return instance;
	}

	public void  registerToken(String token){
		tokenMap.put(token, 0);
	}
	
	public void  remoceToken(String token){
		tokenMap.remove(token);
	}
	
	public String makeToken() {
		String token = (System.currentTimeMillis() + new Random()
				.nextInt(999999999)) + "";

		MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
			byte[] result = md.digest(token.getBytes());

			return Base64Util.byteToBase64(result);

		} catch (NoSuchAlgorithmException e) {
			System.out.println(e.getMessage());
			return null;
		}

	}
	
	public boolean isRsubmit(String token , HttpServletRequest request) {
		
		if(tokenMap.get(token)<SUMBIT_TIME){
			Integer num = tokenMap.get(token);
			tokenMap.remove(token);
			tokenMap.put(token, ++num);
			return false;
		}
		
	
		
		String c_token = request.getParameter("token");
		if (c_token == null) {
			return true;
		}

		String s_token = (String) request.getSession().getAttribute("token");

		if (s_token == null) {
			return true;
		}

		if (!c_token.equals(s_token)) {
			return true;
		}

		return false;
	}
}
